package xyz.chenyongpeng.orderconsumerdubbo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import xyz.chenyongpeng.entity.ZsGTicketsPrice;
import xyz.chenyongpeng.entity.ZsGoodsType;
import xyz.chenyongpeng.entity.ZsOrder;
import xyz.chenyongpeng.orderconsumerdubbo.service.GoodService;
import xyz.chenyongpeng.orderconsumerdubbo.service.OrderService;
import xyz.chenyongpeng.orderconsumerdubbo.service.UserService;
import xyz.chenyongpeng.to.GoodsTo;
import xyz.chenyongpeng.to.TicketPriceList;
import xyz.chenyongpeng.userconsumerdubbo.service.VisitorsService;
import xyz.chenyongpeng.utils.HtmlUtil;
import xyz.chenyongpeng.utils.R;
import xyz.chenyongpeng.utils.XMLUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/Order")
public class OrderController {

    @Autowired
    private UserService userService;

    @Autowired
    private GoodService goodService;

    @Autowired
    private VisitorsService visitorsService;

    @Autowired
    private OrderService orderService;

    /**
     * 填写各种订单信息的首页
     * @param wx_openid
     * @param goods_id
     * @param gt_id
     * @return
     */
    @PostMapping("/index")
    public R index(@RequestParam(name = "wx_openid",required = true) String wx_openid,
                  @RequestParam(name = "goods_id",required = true) String goods_id,
                  @RequestParam(name = "gt_id",required = false) String gt_id){
        if (StringUtils.isEmpty(wx_openid)){
            return R.error(403, "没有登录");
        }

        if (StringUtils.isEmpty(goods_id)){
            return R.error(500, "参数不全");
        }
        String u_id = userService.getUserIdByOpenid(wx_openid);

        GoodsTo goodsTo = goodService.getOne(goods_id);

        if (goodsTo == null){
            return R.error(404, "没有这个商品");
        }

        ZsGoodsType zsGoodsType = goodService.getOneType(goodsTo.getGt_id());
        String tb_name = "zs_"+ zsGoodsType.getTblName();

        Map<String, Object> goodsAttr = goodService.getGoodsAttr(tb_name, goods_id);

        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("goods_id", goodsTo.getGoods_id());
        dataMap.put("goods_info", HtmlUtil.html2Text(goodsTo.getGoods_info()));
        dataMap.put("goods_title", goodsTo.getGoods_title());
        dataMap.put("is_appointment", goodsTo.getIs_appointment());
        dataMap.put("fee_purchase_note", StringUtils.isEmpty(goodsAttr.get("fee_purchase_note")) == true ?"":goodsAttr.get("fee_purchase_note"));

        Map<String,Object> priceList = new HashMap<>();
        priceList.put("ticket_type", 99);
        priceList.put("price", goodsTo.getPrice());
        priceList.put("ori_price", goodsTo.getOri_price());
        priceList.put("discount_amount", goodsTo.getDiscount_amount());

        dataMap.put("priceList", priceList);


        if (goodsTo.getGt_id() == 1){
            if ("1".equals(goodsAttr.get("is_group"))){
                dataMap.put("min", goodsAttr.get("min"));
                dataMap.put("max", goodsAttr.get("max"));
                dataMap.put("is_group", goodsAttr.get("is_group"));
                dataMap.put("group", goodService.getGroups(goods_id));
            }
        }else if (goodsTo.getGt_id() == 2){
            if ("0".equals(goodsAttr.get("is_appointment"))){
                List<ZsGTicketsPrice> zsGTicketsPriceList = goodService.getAllTicketPrice(goods_id);
                if (zsGTicketsPriceList.size() != 0){
                    dataMap.put("priceList", zsGTicketsPriceList);
                }else {
                    Map<String,Object> priceList2 = new HashMap<>();
                    priceList.put("ticket_type", 1);
                    priceList.put("price", goodsTo.getPrice());
                    priceList.put("ori_price", goodsTo.getOri_price());
                    priceList.put("discount_amount", goodsTo.getDiscount_amount());
                    dataMap.put("priceList", priceList2);
                }
            }
        }else if(goodsTo.getGt_id() == 4){

        }

        if (!StringUtils.isEmpty(u_id)){
            dataMap.put("coupon", goodService.getCouponListByGoodsId(goods_id,null,u_id));
            dataMap.put("visitors", visitorsService.getListByUId(u_id, "0,5"));
        }
        return R.ok(dataMap);
    }


    /**
     * 提交订单
     * @param wx_openid
     * @param goods_id
     * @param contact_tel
     * @param v_ids
     * @param ticket_type
     * @param quantity
     * @param start_time
     * @param end_time
     * @param contact_name
     * @param contact_id_card
     * @param code_id
     * @return
     */
    @PostMapping("/post")
    public R post(@RequestParam(name = "wx_openid",required = true) String wx_openid,
                  @RequestParam(name = "goods_id",required = true) String goods_id,
                  @RequestParam(name = "contact_tel ",required = true) String contact_tel,
                  @RequestParam(name = "v_ids ",required = false) String v_ids,
                  @RequestParam(name = "ticket_type ",required = false) String ticket_type,
                  @RequestParam(name = "quantity ",required = false) String quantity,
                  @RequestParam(name = "start_time ",required = false) String start_time,
                  @RequestParam(name = "end_time ",required = false) String end_time,
                  @RequestParam(name = "contact_name ",required = false) String contact_name,
                  @RequestParam(name = "contact_id_card ",required = false) String contact_id_card,
                  @RequestParam(name = "code_id ",required = false) String code_id
                  ){
        if (!StringUtils.isEmpty(start_time)) {
            if (start_time.length() > 10){
                start_time = start_time.substring(0,10);
            }
        }
        if (!StringUtils.isEmpty(end_time)) {
            if (end_time.length() > 10){
                end_time = end_time.substring(0,10);
            }
        }

        String u_id = userService.getUserIdByOpenid(wx_openid);
        if (StringUtils.isEmpty(u_id)){
            return R.error(500, "没有这个用户");
        }

        GoodsTo goodsTo = goodService.getOne(goods_id);

        if (goodsTo != null){
            if (goodsTo.getGt_id() == 2){
                if (goodsTo.getPrice_lists().size() == 0){
                    TicketPriceList priceList = new TicketPriceList(
                            goodsTo.getPrice_lists().get(0).getPrice(),
                            goodsTo.getPrice_lists().get(0).getOri_price(),
                            goodsTo.getPrice_lists().get(0).getDiscount_amount()
                    );
                }
            }
        }

        if (!StringUtils.isEmpty(code_id)){

        }
        return null;
    }

    /**
     * 获取订单列表
     * @param wx_openid
     * @param is_appointment
     * @param limit
     * @param is_refund
     * @param status
     * @return
     */
    @PostMapping("/list")
    public R list(@RequestParam(name = "wx_openid",required = true) String wx_openid,
                  @RequestParam(name = "is_appointment ",required = true) String is_appointment,
                  @RequestParam(name = "limit ",required = false) String limit,
                  @RequestParam(name = "is_refund ",required = false) String is_refund,
                  @RequestParam(name = "status ",required = false) String status){
        return null;
    }

    /**
     * 获取微信返回的预定单代码
     * @param wx_openid
     * @param order_sn
     * @return
     */
    @PostMapping("/payment")
    public R payment(@RequestParam(name = "wx_openid",required = true) String wx_openid,
                     @RequestParam(name = "order_sn ",required = true) String order_sn){
        return null;
    }

    /**
     * 删除订单
     * @param wx_openid
     * @param order_sn
     * @return
     */
    @PostMapping("/del")
    public R del(@RequestParam(name = "wx_openid",required = true) String wx_openid,
                 @RequestParam(name = "order_sn ",required = true) String order_sn){
        String u_id = userService.getUserIdByOpenid(wx_openid);

        if (StringUtils.isEmpty(u_id)){
            return R.error(404, "没有这个用户");
        }

        ZsOrder zsOrder = orderService.find(order_sn, u_id);
        if (zsOrder == null){
            return R.error(404, "找不到这个订单");
        }
        orderService.delOneOrder(zsOrder);
        return R.ok();
    }

    /**
     * 获取订单详情
     * @param wx_openid
     * @param order_sn
     * @return
     */
    @PostMapping("/details")
    public R details(@RequestParam(name = "wx_openid",required = true) String wx_openid,
                 @RequestParam(name = "order_sn ",required = true) String order_sn){
        String u_id = userService.getUserIdByOpenid(wx_openid);
        if (StringUtils.isEmpty(u_id)){
            return R.error(404, "没有这个用户");
        }
        ZsOrder zsOrder = orderService.getOneByOrderSn(order_sn);
        if (zsOrder == null){
            return R.error(404, "找不到这个订单");
        }
        if (zsOrder.getSpanTime() !=null || zsOrder.getSpanTime() != 0){
            // 如果是预约订单 存在 时段
        }

        Map<String,Object> result = new HashMap<>();
        result.put("order", zsOrder);

        return null;
    }

    /**
     * 退款
     * @param wx_openid
     * @param order_sn
     * @param refund_reason
     * @param refund_amount
     * @return
     */
    @PostMapping("/refund")
    public R refund(@RequestParam(name = "wx_openid",required = true) String wx_openid,
                    @RequestParam(name = "order_sn ",required = true) String order_sn,
                    @RequestParam(name = "refund_reason ",required = true) String refund_reason,
                    @RequestParam(name = "refund_amount  ",required = true) String refund_amount ){
        return null;
    }

    /**
     * 订单可退款金额查询
     * @param wx_openid
     * @param order_sn
     * @return
     */
    @PostMapping("/refundableAmount")
    public R refundableAmount(@RequestParam(name = "wx_openid",required = true) String wx_openid,
                              @RequestParam(name = "order_sn ",required = true) String order_sn){
        return null;
    }

    /**
     * IOS端通过微信公众号购买音频订单提交接口
     * @param unionid
     * @param order_sn
     * @param goods_id
     * @param total_amount
     * @param nickname
     * @return
     */
    @PostMapping("/wxOrder")
    public R wxOrder(@RequestParam(name = "unionid",required = true) String unionid,
                     @RequestParam(name = "order_sn",required = true) String order_sn,
                     @RequestParam(name = "goods_id",required = true) String goods_id,
                     @RequestParam(name = "total_amount",required = false) String total_amount,
                     @RequestParam(name = "nickname",required = false) String nickname){
        return null;
    }

    /**
     * IOS端通过微信公众号购买音频成功后，设置订单状态为已支付
     * @param unionid
     * @param order_sn
     * @return
     */
    @PostMapping("/wxPaySuccess")
    public R wxPaySuccess(@RequestParam(name = "unionid",required = true) String unionid,
                          @RequestParam(name = "order_sn",required = true) String order_sn){
        return null;
    }

    /**
     * 支付成功回调
     * @param request
     * @param response
     */
    public void getJSSDKCallbackData(HttpServletRequest request, HttpServletResponse response) {
        try {
            synchronized (this) {
                Map<String, String> kvm = XMLUtil.parseRequestXmlToMap(request);
                if (com.github.binarywang.wxpay.util.SignUtils.checkSign(kvm, null, "商户密钥")) {
                    if (kvm.get("result_code").equals("SUCCESS")) {
                        System.out.println("微信服务器返回支付成功且回调小程序支付成功接");
                        response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[ok]]></return_msg></xml>");
                    } else {
                        System.out.println("微信服务器通知此回调接口支付失败后，通知给业务系统做处理");
                        response.getWriter().write(
                                "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[result_code is FAIL]]></return_msg></xml>");
                    }
                } else {
                    System.out.println("微信服务器通知此回调接口支未知。。。。，通知给业务系统做处理");
                    response.getWriter().write(
                            "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[check signature FAIL]]></return_msg></xml>");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
